from email.header import Header
from email.mime.text import MIMEText
import smtplib
import urllib3
from bs4 import BeautifulSoup
import requests
import time
def get_url():
    #获取网站的通知网站列表，返回通知地址列表
    header = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"}
    url='https://gs.njust.edu.cn/'
    r=requests.get(url=url,headers=header)
    soup=BeautifulSoup(r.text,features='html.parser')
    links=soup.findAll('li',attrs={'class':'_rollPar'})
    url_list=[]
    for link in links:
        a=link.a['href']
        if a.endswith('htm'):
            url_list.append(url+a)
    return url_list

def get_content():
    #获取网页通知地址的实际内容，包括发布时间、主题和链接
    title_list=[]
    url_list=get_url()
    header = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"}
    for url in url_list:
        r=requests.get(url=url,headers=header)
        r.encoding='utf-8'
        soup=BeautifulSoup(r.text,features='html.parser')
        title=soup.find('h3',attrs={'class':'title'}).text
        pub_time=soup.find('div',attrs={'class':'infoA'}).find('span').text
        current_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        if pub_time==current_time:
            title_list.append('主题：'+title+',时间：'+pub_time+'，详情点击：'+url+'\n')
    #删除重复列表元素
    result_list=[]
    for list in title_list:
        if list not in result_list:
            result_list.append(list)
    return result_list

def send_email(mail_body,rec):
    #给特定邮箱发送包含特定内容的邮件，可以拓展为群发邮件
    sender='1589978621@qq.com'
    receiver=rec
    server_host='smtp.qq.com'
    username='1589978621@qq.com'
    #这里改为自己的邮箱授权码
    password='****************'
    current_time = time.strftime('%Y年%m月%d日', time.localtime(time.time()))
    mail_title=current_time+'研究生院新通知，画手开发'
    message=MIMEText(''.join(mail_body),'plain','utf-8')
    message['Accept-Language']='zh-CN'
    message['Accept-Charset']='ISO-8859-1,utf-8'
    message['From']=sender
    message['To']=','.join(receiver)
    message['Subject']=Header(mail_title,'utf-8')
    try:
        smtp=smtplib.SMTP()
        smtp.connect(server_host)
        smtp.login(username,password)
        smtp.sendmail(sender,receiver,message.as_string())
        print('邮件发送成功!')
        smtp.quit()
    except smtplib.SMTPException:
        print('邮件发送失败!')

def get_mailbox(file):
    mail_list=[]
    f=open(file,encoding='gbk',errors='ignore')
    lines=f.readlines()
    f.close()
    for line in lines:
        line=line.replace('\n','')
        mail_list.append(line)
    #去除重复项
    mail_list=list(set(mail_list))
    return mail_list

def test():
    #测试函数，看功能是否正常
    file='mail_information.txt'
    mail_list=get_mailbox(file)
    urllib3.disable_warnings()
    content=get_content()
    print(content)
    if len(content)==0:
        pass
        #send_email('今天南理工研究生院没有新通知',mail_list)
    else:
        send_email(content,mail_list)
    return None

if __name__=='__main__':
    test()